package com.hqbzl.c1.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TestCyclicBarrier {
    //barrier.await(); 之后的代同时执行
    public static void main(String[] args) {
        final CyclicBarrier barrier = new CyclicBarrier(2);
        System.out.println("barrier.getNumberWaiting() = " + barrier.getNumberWaiting());
        System.out.println("barrier.getParties() = " + barrier.getParties());
        new Thread(() -> {
            try {
                log.debug("th1 next");
                barrier.await();
                log.debug("th1 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, "th1").start();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                log.debug("th2 next");
                barrier.await();
                log.debug("th1 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, "th2").start();
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                log.debug("th3 next");
                barrier.await();
                log.debug("th3 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, "th3").start();
        System.out.println("barrier.getNumberWaiting() = " + barrier.getNumberWaiting());
        System.out.println("barrier.getParties() = " + barrier.getParties());
    }
}
